/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Other;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 *
 * @author Envy
 */
public class LoadKeyPair {

    private KeyPair LoadKeyPair() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
        //Load public
        File pf = new File("pub");
        byte[] s = new byte[(int) pf.length()];
        FileInputStream fin = new FileInputStream(pf);
        fin.read(s);
        fin.close();
        //Load private
        File pvf = new File("prv");
        byte[] ss = new byte[(int) pvf.length()];
        FileInputStream fin1 = new FileInputStream(pvf);
        fin1.read(ss);
        fin1.close();

        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(s);
        PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

        PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(ss);
        PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);

        return new KeyPair(publicKey, privateKey);
    }

    private KeyPair LoadKeyPairX() throws Exception {

        //Load public
        File pf = new File("pubs");
        byte[] s = new byte[(int) pf.length()];
        FileInputStream fin = new FileInputStream(pf);
        fin.read(s);
        fin.close();
        //Load private
        File pvf = new File("prvs");
        byte[] ss = new byte[(int) pvf.length()];
        FileInputStream fin1 = new FileInputStream(pvf);
        fin1.read(ss);
        fin1.close();

        KeyFactory keyFactory = KeyFactory.getInstance("DSA", "SUN");
        X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(s);
        PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

        PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(ss);
        PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);

        return new KeyPair(publicKey, privateKey);
    }
}
